class AdminController < ApplicationController
  before_filter :before
  
  def index

  end

  def update
    @proposal = Proposal.find(params[:id])

    @proposal.update_attributes(params[:proposal])
    redirect_to '/admin/'
   
  end
  
  def show
    @proposal = Proposal.find(params[:id])
    @documents = @proposal.documents.find(:all)
    @reviews = @proposal.reviews.find(:all)
    @users = User.find(:all, :conditions => { :role => "reviewer" }, :order => "name")
    if ENV['RAILS_ENV'] == "development"
      @users = User.find(:all, :conditions => { :role => "admin" }, :order => "name")
    end
  end
  
  def create_review
    @proposal = Proposal.find(params[:proposal_id])
    @reviews = @proposal.reviews.find(:all)
    
    if @proposal.reviews.find(:first, :conditions => { :user_id => params[:user_id]})
        flash[:error] = "there is already a review"
        redirect_to '/admin/show/' + @proposal.id.to_s
    else
      
    end
    
    
    @review = @proposal.reviews.build(params[:review])


   @review.user = User.find(params[:user_id])
   @review.save
       redirect_to '/admin/show/' + @proposal.id.to_s


  end
  
  def save_note
    @proposal = Proposal.find(params[:proposal_id])
    if @proposal.update_attributes(params[:proposal])
      flash[:notice] = 'Proposal was successfully updated.'
    end
    redirect_to request.referer
  end
    

  def delete
    @proposal = Proposal.find(params[:proposal_id])
    @review = @proposal.reviews.find(:first, :conditions => { :user_id => params[:user_id]})    
    
    @review.destroy
    redirect_to '/admin/show/' + @proposal.id.to_s

  end
  
  def start_review
    @proposal = Proposal.find(params[:id])
    @proposal.status = "under review"
    @sent_mails_to = ""
    
    @reviews = @proposal.reviews.find(:all)
    @reviews.each do |r| 
      r.status = "open"
      @user = User.find(r.user_id)
      @sent_mails_to = @sent_mails_to + "<br>" + @user.email
      Emailer.deliver_review_assigned(@user.email, @proposal)

      if r.save
      end
    end
  
    @proposal.save
    flash[:notice] = "Email wurde versandt an: <br>" + @sent_mails_to
    redirect_to '/admin/show/' + @proposal.id.to_s
  end
  
  def statistics
  end
  
  
  def before
    unless session[:user_id].nil?
      @user = User.find(session[:user_id])
      unless @user.role == "admin"
        flash[:error] = "Kein Zugriffsrecht"
        redirect_to "/"
      end
    else
      redirect_to "/"
    end
      
    
    unless @status = params[:status]
      @status = "submitted"
    end
    
    @proposals = Proposal.find(:all, :conditions => {:status => @status })
    @proposals_new = Proposal.find(:all, :conditions => {:status => "new" })
    @proposals_submitted = Proposal.find(:all, :conditions => {:status => "submitted" })
    @proposals_under_review = Proposal.find(:all, :conditions => {:status => "under review" })
    @proposals_reviewed = Proposal.find(:all, :conditions => {:status => "reviewed" })
  end  
  
end
